<template>
  <div id="management" >
    <el-col>
      <div class="grid-content bg-purple-dark span_blo" style="width:100%;">
        <ul class="management_List">
          <li slot="reference" style="color:#FF3B30;font-size: 15px;cursor: pointer;" @click="open">
            <span>文档管理需知 </span>
            <i class="iconfont">&#xe639;</i>
          </li>
          <li class="item">
            <span style="color:#bfc8d8">剩余:</span>
            <p style="color:#FF3B30">{{fileSpace.fileSpaceSurplusSize}}M</p>
          </li>
          <li class="item">
            <span style="color:#bfc8d8">空间容量:</span>
            <p style="color:#32CD32">{{fileSpace.fileSpaceSize}}M</p>
          </li>
        </ul>
      </div>
    </el-col>
    <div v-if="!isicon" class="demo-image">
      <div class="block" v-for="fit in Listofdocuments" :key="fit.documentid">
        <el-tooltip placement="top">
          <div slot="content">
            <div style="width:170px;">
              <p @click="Theonlinepreview(fit.fileUrl)" style="cursor:pointer;text-align:center;padding-bottom:5px;font-size:15px">预览</p>
            </div>
          </div>
          <div class="block_count">
            <el-image :src="fit.fileUrl">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span class="imagename">{{fit.fileName}}</span>
          </div>
        </el-tooltip>
        <el-checkbox v-if="bitchdelete" v-model="fit.checked" @change="pitchChoice(fit.documentid,fit.checked)"></el-checkbox>
      </div>
    </div>
    <div v-if="isicon" class="iconCount">
      <img src="@/assets/images/available.png" />
      <p>sorry! 暂无文档~</p>
    </div>
    <!-- 上传弹框 -->
    <el-dialog customClass="upload"  modal-append-to-body  title="上传文件" top="25vh" :modal="false" :visible.sync="isShow">
      <el-upload
        class="upload-demo"
        ref="upload"
        action="fakeaction"
        :limit="3"
        :http-request="uploadSectionFile"
        :file-list="fileList"
        :on-change="addFile"
        :on-exceed="exceed"
        :on-remove="deleteFile"
        :before-upload="beforeAvatarUpload"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary" round>添 加</el-button>
      </el-upload>
      <div class="dialog_footer">
          <el-button size="small" type="primary" :loading="btnloading" @click="changeDep" round>开始上传</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import serUrl from '@/config/serverAddress';
export default {
  props: ['input', 'bitchdelete'],
  components: {
  },
  data () {
    return {
      Listofdocuments: [{ // 文档列表
        documentid: '', // 唯一ID
        DocIcon: '', // 文档小图标地址
        DocName: '', // 文档名称
        DocSize: '', // 文档大小
        DocSuffix: '', // 文档后缀名
        DocTime: '', // 文档上传时间
        DocUrl: '', // 文档所在服务器地址
        DocUser: ''// 文档所属客户
      }],
      fileSpace: {
        TotalSpace: '1024', // 文档总容量MB
        TotalSpaceSurplus: '1017.55'// 剩余总容量
      },
      isicon: true, // 有无数据
      isShow: false, // 上传弹框
      DocIDS: [],
      manloading: false,
      
      url: '',
      fileLists: [],
      delDepParams: {}, // 删除弹框和参数
      notify: true,
      fileData: '',
      fileList: [],
      btnloading: false,
      typeArr: ['jpg', 'jpge', 'png', 'bmp', 'gif', 'zip', 'rar', 'jar', 'tar', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pps', 'ppsx', 'txt', 'pdf']
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.common.userInfo,
      subid: state => state.companyInfo.subid,
      accountId: state => state.companyInfo.accountId,
    })
  },
  methods: {
    beforeAvatarUpload(file) {
      let arr = file.name.split('.');
      let type = arr[arr.length - 1];
      let isAfi = this.typeArr.find(res=>{
        return res == type;
      });
      if (!isAfi) {
        this.$message({
          message: `暂不支持上传${ type }类型文件!`,
          type: 'warning'
        });
      }
      return isAfi ? true : false;
    },
    uploadSectionFile (file) { // 添加文档
      let fileData = new FormData(); // new formData对象
      fileData.append('formFileData', file.file); // append增加数据
      fileData.append('subid', this.subid);
      if(this.accountId) {
        fileData.append('accountId', this.accountId);
      }
      this.btnloading = true;
      this.manloading = true;
      this.$api.accountPort.UploadDocument(fileData).then(res => {
        let result = res.data;
        if (result.status === 200) {
          this.isShow = false;
          this.$message({
            message: '文档添加成功',
            type: 'success'
          });
          this.Getthedocument();
          this.getFilepace();
          this.$refs.upload.clearFiles();
          this.fileList = [];
        }else if(result.status == 409) {
          this.$message({
            message: result.data[0].FileName + result.message,
            type: 'warning'
          });
        }
        this.btnloading = false;
        this.manloading = false;
      }).catch(err=>{
        this.btnloading = false;
        this.manloading = false;
      });
    },
    addFile (file, fileList) {
      let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name);
      if (existFile) {
        this.$message.error('当前文件已经存在!');
        fileList.pop();
      }
      this.fileList = fileList;
    },
    deleteFile(file, fileList) {
      this.fileList = fileList;
    },
    changeDep () { // 添加文档
      if (this.fileList.length === 0) {
        this.$message({ message: '请先选择文件', type: 'warning' });
      }else{
        this.$refs.upload.submit(); // 提交调用uploadFile函数
      }
    },
    Getthedocument () { // 获取文档
      this.url = serUrl; // 获取地址
      let params = {
        subid: this.subid,
        keyWord: this.input
      };
      this.manloading = true;
      this.$api.accountPort.DocumentPageList(params).then(res => {
        let result = res.data;
        if (result.status === 200) {
          this.Listofdocuments = res.data.data;
          if (this.Listofdocuments.length === '0') {
            this.isicon = true;
          } else {
            this.isicon = false;
            this.Listofdocuments.map(item => {
              this.$set(item, 'checked', false); // 这里，给对象添加属性，用$set方法。
              return item;
            });
          }
          this.manloading = false;
          this.DocIDS = [];
        } else if (result.Status === 401) {
          this.isicon = true;
          this.manloading = false;
        }else{
          this.isicon = true;
          this.manloading = false;
        }
      });
    },
    getFilepace() {
      this.$api.accountPort.GetSpaceInfo().then(res=>{
        if(res.data.status == 200) {
          this.fileSpace = res.data.data;
        }
      });
    },
    
    Deletedocument () { // 删除文档
      this.$api.accountPort.DeleteDocument(this.DocIDS).then(res => {
        let result = res.data;
        if (result.status === 200) {
          this.$message({
            message: '文档删除成功',
            type: 'success'
          });
          this.Getthedocument();
          this.getFilepace();
        }
      });
    },
    completelyDelete () { // 删除弹框和参数
      if (this.DocIDS.length == 0) {
        this.$message({
          message: '至少选择一个文档',
          type: 'warning'
        });
        return;
      }
      this.$confirm('删除后文档数据不可恢复,请谨慎删除', '删除文档', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.Deletedocument();
      }).catch(() => {
      });
    },
    removeChoice (arr, val) { // 删除数组指定元素
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].documentid === val) {
          arr.splice(i, 1);
          break;
        }
      }
    },
    pitchChoice (result, ischeck) { // 选框
      if (ischeck) {
        this.DocIDS.push({ documentid: result });
      }
      if (!ischeck) {
        this.removeChoice(this.DocIDS, result);
      }
    },
    Theonlinepreview (url) { // 在线预览
      window.open(url);
    },
    open () {
      if (this.notify) {
        this.notify = false;
        this.$notify({
          message: '文档管理模块需知:一个企业号下能使用免费容量为1GB(1024M),如需开通更多容量,请联系： 010-89648111;（500元/10GB/年，10GB起购）。',
          offset: 240
        });
        setTimeout(() => {
          this.notify = true; 
        }, 7000);
      }
    },
    dataURItoBlob (dataURI, type) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
    exceed () {
      this.$message({
        message: '已到最大允许上传个数',
        type: 'warning'
      });
    },
  },
  mounted () {
    this.Getthedocument();
    this.getFilepace();
  }
};
</script>
<style lang="less">
#management{
  width: 100%;
  height: 100%;
   .el-col-24 {
      width: 94%;
      height: 40px;
      margin-left: 2.5%;
      box-shadow: 0px 0px 8px #d4dcf0;
      border: none;
      margin-top: 1%;
      background-color: #f7f8fc;
      .management_List{
        float: left;
        width: 100%;
        li {
          float: right;
          margin-right: 3%;
          line-height: 40px;
          p{
            float: right;
            font-size: 15px;
            padding-left: 7px;
          }
        }
      }
    }
    .demo-image {
      width: 94.5%;
      float: left;
      margin-top: 20px;
      margin-left: 25px;
      .block{
        float: left;
        margin: 0 25px;
        .el-image{
          width: 120px;
          height: 150px;
          margin-top: 15px;
        }
        .el-checkbox{
        display: block;
        text-align: center
      }
      .block_count{
        width: 180px;
        height: 220px;
        border: 1px solid #d4dcf0;
        text-align: center;
      }
      }
      .imagename{
        word-wrap: break-word;
        overflow: hidden;
        display: block;
        width: 100%;
        height: 50px;
        text-align: center;
      }
      .image-slot{
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        i{
          font-size: 40px;
          color: #ccc;
        }
      }
    }
    .iconCount{
      width: 100%;
      float: left;
      height: 90%;
      text-align: center;
      img{
        width: 320px;
        height: 220px;
        margin-top: 100px
      }
      p{
        text-align: center;
        color: #C6C6C6;
        font-size: 18px;
        margin-top: 20px
      }
    }
    .el-dialog__wrapper{
       z-index: 99;
    }
  .upload{
    width: 390px;
    min-height: 260px;
    position: absolute;
    right: 16%;
    z-index: 999;
    .el-dialog__header{
      padding: 10px 20px;
      .el-dialog__headerbtn{
        font-size: 20px;
        top: 15px;
      }
      .el-dialog__title{
        font-weight: 500;
      }
    }
    .el-dialog__body {
      padding: 2% 0;
    }
    .upload-demo{
      padding: 0 10px;
      min-height: 260px;
    }
    .dialog_footer{
      border-top: 1px solid #e0dcdc;
      text-align: right;
      height: 45px;
      line-height: 45px;
      padding-right: 20px;
    }
  }
}
</style>
